import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class Skey_RSA{
    public static void main(String args[]) throws Exception{
        KeyPairGenerator kpg= getRsa();
        kpg.initialize(1024);
        KeyPair kp=kpg.genKeyPair();
        PublicKey pbkey=kp.getPublic();
        PrivateKey prkey=kp.getPrivate();
        //  保存公钥
        FileOutputStream  f1= getFileOutputStream("Skey_RSA_pub.dat");
        ObjectOutputStream b1= getObjectOutputStream(f1);
        b1.writeObject(pbkey);
        //  保存私钥
        FileOutputStream  f2= getFileOutputStream("Skey_RSA_priv.dat");
        ObjectOutputStream b2= getObjectOutputStream(f2);
        b2.writeObject(prkey);
    }

    private static ObjectOutputStream getObjectOutputStream(FileOutputStream f2) throws IOException {
        return new ObjectOutputStream(f2);
    }

    private static FileOutputStream getFileOutputStream(String name) throws FileNotFoundException {
        return new FileOutputStream(name);
    }

    private static KeyPairGenerator getRsa() throws NoSuchAlgorithmException {
        return KeyPairGenerator.getInstance("RSA");
    }
}